package com.kakavr.alipay.service;

import java.math.BigDecimal;
import java.util.Map;

import javax.annotation.Resource;

import org.joda.time.DateTime;
import org.springframework.stereotype.Service;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayFundTransToaccountTransferRequest;
import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;
import com.beust.jcommander.internal.Maps;
import com.kakavr.alipay.dao.IAliTransferDao;
import com.kakavr.base.service.BaseService;
import com.kakavr.pay.util.AlipayUtil;
import com.kakavr.pay.util.WXPayUtil;
import com.kakavr.util.ConvertUtils;

@Service
public class AliTransferService extends BaseService implements
		IAliTransferService {
	@Resource
	private IAliTransferDao aliTransferDao;

	@Override
	public int addSplitPayLog(Object storeId, Object payeeAccount,
			Object splitId, BigDecimal money) {
		int returnInt = 2;
		AlipayClient alipayClient = AlipayUtil.getAlipayClient();
		AlipayFundTransToaccountTransferRequest request = new AlipayFundTransToaccountTransferRequest();
		Map<String, Object> bizMap = Maps.newHashMap();
		bizMap.put("out_biz_no", WXPayUtil.getCurrentTimestampMs());
		bizMap.put("payee_type", "ALIPAY_LOGONID");
		bizMap.put("payee_account", payeeAccount);
		bizMap.put("amount", money);
		bizMap.put("remark", "卡卡VR分账");
		request.setBizContent(ConvertUtils.toJson(bizMap));
		try {
			AlipayFundTransToaccountTransferResponse response = alipayClient
					.execute(request);
			if (response.isSuccess()) {
				returnInt = 1;
			}
			bizMap.put("msg", response.getMsg());
			bizMap.put("sub_code", response.getSubCode());
			bizMap.put("sub_msg", response.getSubMsg());
			bizMap.put("order_id", response.getOrderId());
			bizMap.put("pay_date", response.getPayDate());
		} catch (AlipayApiException e) {
			error("支付宝分账出错，错误信息：" + e);
		}
		bizMap.put("createTime", DateTime.now().toDate());
		bizMap.put("splitId", splitId);
		bizMap.put("storeId", storeId);
		bizMap.put("status", returnInt);
		aliTransferDao.insertSplitAlipayLog(bizMap);
		return returnInt;
	}

}
